<template>
  <div>
    <goodsSwiper v-if="goodsSku.data" :res="goodsSku" />
    <div card py-36rpx w-full>
      <div px-36rpx>
        <div font-bold text-30rpx>{{ goodsSku.data.goodsName }}</div>
        <div my-20rpx flex flex-a-c>
          <div mr-10px text-main-color font-bold text-36rpx>
            {{ unitPrice(activityData.surplusPrice, '￥') }}
          </div>
          <!-- 普通商品 -->
          <div text-26rpx text-warmgray line-through>
            原价{{ unitPrice(goodsSku.data.price, '￥') }}
          </div>
        </div>
        <div color-warmGray text-24rpx>
          {{ goodsSku.data.sellingPoint || "" }}
        </div>
      </div>
      <div px-36rpx mt-40rpx>
        <nut-progress :stroke-color="colors.themeColor" :percentage="totalPercent" />
        <div text-24rpx color-warmGray mt-20rpx flex flex-a-c flex-j-sb>
          <div>已砍{{ cutPrice }}元</div>
          <div>还剩{{ activityData.surplusPrice }}元</div>
        </div>
      </div>
    </div>
    <div card p-36rpx>
      <div v-if="isHelpBargain">
        <nut-button class="share" block type="primary" @click="help">帮忙砍价</nut-button>
      </div>
      <div v-else>
        <nut-button v-if="!activityData.pass && activityData.status != 'END'" class="share" block type="primary"
          @click="share">邀请砍价</nut-button>

        <div v-else>
          <nut-button v-if="activityData.status != 'END'" class="share" block type="warning"
            @click="bill">立即购买</nut-button>
        </div>
      </div>
    </div>
    <div mt-40rpx card p-36rpx>
      <div class="goods-active" :style="gradient">帮忙砍</div>
      <div v-if="offerHelpList.length" mt-40rpx>
        <div v-for="(item, index) in offerHelpList" my-20rpx :key="index">
          <div flex flex-a-c flex-j-sb>
            <div flex flex-a-c>
              <div>
                <image class="circle" w-75rpx h-75rpx :src="item.kanjiaMemberFace" />
              </div>
              <div>
                <div>{{ noPassByName(item.kanjiaMemberName) }}</div>
                <div text-24rpx>使出吃的奶劲儿</div>
              </div>

            </div>
            <div>砍掉<span text-main-color>￥{{ item.kanjiaPrice }}元</span></div>
          </div>
        </div>
      </div>
    </div>
    <div mt-40rpx card p-36rpx>
      <div class="goods-active" :style="gradient">商品介绍</div>
      <goodsIntro :res="goodsSku?.data.mobileIntro" />
    </div>
    <nut-popup round position="bottom" :custom-style="{ height: '400rpx' }" v-model:visible="bargaining">
      <div h-400rpx flex flex-a-c flex-j-c>
        <div w-full px-32rpx h-400rpx text-40rpx text-center flex flex-col flex-j-sb>
          <div mt-50rpx>
            恭喜您砍掉了
          </div>
          <div text-main-color text-62rpx font-bold>
            {{ unitPrice(residual, '') }}元
          </div>
          <div w-full mb-20rpx>
            <nut-button @click="bargaining = false" block type="primary">关闭</nut-button>
          </div>
        </div>
      </div>
    </nut-popup>
    <shareModel ref="shareRef" />
    <nut-toast ref="toastRef" />
  </div>
</template>

<script setup lang="ts">
import goodsSwiper from '@/components/goods/template/goods-swiper.vue';
import { getBargainDetail, getBargainActivity, launchBargain, getBargainLog, helpBargain } from "@/api/promotion";
import { onLoad, onShareAppMessage } from "@dcloudio/uni-app";
import { unitPrice, noPassByName } from '@/utils/filters';
import { colors } from '@/constants/injection-key';
import goodsIntro from '@/components/goods/template/goods-intro.vue'; //商品介绍
import shareModel from '@/components/share/index.vue';
import type { ToastInst } from 'nutui-uniapp';
import { billOrder } from '@/api/trade';
const toastRef = ref<ToastInst>()
const shareRef = ref<any>('')
const routerVal = ref<any>('')
const goodsSku = ref<any>({
  data: {
    goodsGalleryList: []
  }
})
const offerHelpList = ref<any>([])
const gradient = { '--gradient-left': colors.themeColor, '--gradient-right': colors.disabledLightColor }
const result = ref<any>('')
const activityData = ref<any>({}) //砍价活动详情
const bargaining = ref<boolean>(false)
const residual = ref<number>(0) //砍价金额
const totalPercent = ref<number>(0) //总百分比

const cutPrice = ref<any>(0) //已砍金额
const isHelpBargain = ref<boolean>(false)
const params = ref<any>({
  kanjiaActivityGoodsId: ''
})

async function bill() {
  let data = {
    skuId: goodsSku.value.data.id,
    num: 1,
    id: routerVal.value.id,
    cartType: "KANJIA"
  };
  toastRef.value?.showToast['loading']('加载中', {
    cover: true,
    duration: 0
  })

  const res = await billOrder(data);
  if (res.data.success) {
    toastRef.value?.hideToast();
    uni.navigateTo({
      url: `/pages/mine/order/fillorder?way=${data.cartType}`
    });
  }
  else {
    toastRef.value?.hideToast();
  }
}

async function init() {
  const res = await getBargainDetail(routerVal.value.id)
  if (res.data.success) {

    goodsSku.value.data = res.data.result.goodsSku
    goodsSku.value.data.goodsGalleryList = res.data.result.goodsSku.thumbnail.split(',')
    uni.setNavigationBarTitle({
      title: res.data.result.goodsSku.goodsName || '砍价详情'
    });
    result.value = res.data.result
    join()
  }
}

onShareAppMessage((res: any) => {
  return {
    title: shareRef.value.shareTitle(),
    path: linkPath(),
    imageUrl: goodsSku.value.data.goodsGalleryList[0]
  }
})
const linkPath = () => {
  return "/pages/promotions/bargain/detail?id=" +
    routerVal.value.id +
    "&activityId=" +
    activityData.value.id
}

// 分享
function share() {
  shareRef.value.fill(
    {
      title: goodsSku.value.data.goodsName,
      href: linkPath(),
      imageUrl: goodsSku.value.data.goodsGalleryList[0],
      type: 'kanjia'
    }
  )
  shareRef.value.open()
}

// 参与活动
async function join() {
  const res = await getBargainActivity(params.value)
  if (res.data.success) {
    if (res.data.result.launch) {
      activityData.value = res.data.result
      totalPercent.value = 100 - Math.floor((res.data.result.surplusPrice / goodsSku.value.data.price) * 100);
      cutPrice.value = (goodsSku.value.data.price - activityData.value.surplusPrice).toFixed(2);
      // activityData.value.help = true
      if (activityData.value.id && activityData.value.help) {
        isHelpBargain.value = true
      }
      getBargainLogList();
    } else {
      // 发起砍价
      launch();
    }

  }
}

async function help() {
  let res = await helpBargain(activityData.value.id);
  if (res.data.success) {
    isHelpBargain.value = false;
    residual.value = res.data.result.kanjiaPrice;
    bargaining.value = true;
    // 帮砍完成之后查询帮砍记录
    init();
  } else {
    isHelpBargain.value = false;
  }
}

async function getBargainLogList() {
  const submit: any = {}
  submit.pageNumber = 1
  submit.pageSize = 100
  submit.kanJiaActivityId = activityData.value.id

  const res = await getBargainLog(submit)
  if (res.data.success) {
    offerHelpList.value = res.data.result.records
  }
}

// 发起砍价活动
async function launch() {
  let res = await launchBargain({ id: routerVal.value.id });
  if (res.data.success) {
    residual.value = res.data.result.kanjiaPrice;
    bargaining.value = true;
    // 查询帮砍记录
    init();
  }
}

onLoad((options: any) => {
  routerVal.value = options
  params.value.kanjiaActivityGoodsId = routerVal.value.id
  params.value.kanjiaActivityId = routerVal.value.activityId
  init()
})
</script>

<style scoped lang="scss">
.circle {
  border-radius: 50%;
}

.share {
  animation: mymove 5s infinite;
  -webkit-animation: mymove 5s infinite;
  /*Safari and Chrome*/
  animation-direction: alternate;
  /*轮流反向播放动画。*/
  animation-timing-function: ease-in-out;
  /*动画的速度曲线*/
  /* Safari 和 Chrome */
  -webkit-animation: mymove 5s infinite;
  -webkit-animation-direction: alternate;
  /*轮流反向播放动画。*/
  -webkit-animation-timing-function: ease-in-out;
  /*动画的速度曲线*/
}

.goods-active {
  font-weight: 700;
  position: relative;
  display: inline;
  line-height: 1.75;

  &::before {
    position: absolute;
    left: 50%;
    bottom: -10rpx;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
    content: "";
    display: block;
    width: 52rpx;
    height: 6rpx;
    background-image: linear-gradient(90deg, var(--gradient-left), var(--gradient-right))
  }
}

@keyframes mymove {
  0% {
    transform: scale(1);
    /*开始为原始大小*/
  }

  25% {
    transform: scale(1.1);
    /*放大1.1倍*/
  }

  50% {
    transform: scale(1);
  }

  75% {
    transform: scale(1.1);
  }
}
</style>
